<template>
    <div class="main row">
        <div class="box row">
            <div class="material-icons-outlined close" @click="$emit('close')">
                close
            </div>
            <div class="title">选择图片格式</div>

            <div class="options column">
                <div class="label">
                    <div class="watermark">PNG</div>
                    <text class="desc">通用的位图格式</text>
                </div>
                <van-button class="download" @click="savePic" type="primary" round plain>下载</van-button>
            </div>
        </div>
    </div>
</template>

<script>

import drawPic from "../../utils/drawPic.js";
import { calendar } from "@/lib/calendar.js";
import dayjs from "@/lib/day.js";
import { chineseDate } from "@/lib/day.js";
import PictureCreate from "./pictureCreate";
import Notify from "@/wxcomponents/weapp/dist/notify/notify";
export default {
    components: { PictureCreate },
    props: ["content"],
    computed: {
        date() {
            if (!this.content) return {};
            let Time = new Date(this.content.date);
            if (isNaN(Time.getTime())) Time = new Date();
            const time = dayjs(Time);
            const date = time.toObject();
            const { IDayCn, IMonthCn } = calendar.solar2lunar(
                date.years,
                date.months + 1,
                date.date
            );
            return {
                ...date,
                nongli: IMonthCn + IDayCn,
                weekday: chineseDate.weekdaysShort[time.weekday()],
            };
        },
    },
    data() {
        return {
            lock: false,
            creating: false,
            px: 1,
        };
    },
    methods: {
        getPower() {
            //获取相册授权
            return wx.getSetting().then((res) => {
                if (!res.authSetting["scope.writePhotosAlbum"]) {
                    Notify({
                        type: "success",
                        message: "请给予保存相册的权限",
                        selector: "#editor-notify",
                    });
                    return wx.authorize({
                        scope: "scope.writePhotosAlbum",
                    });
                }
                console.log("已有授权");
                return null;
            });
        },
        async downloadCard() {
            try {
                const query = wx.createSelectorQuery();
                query
                    .select("#myCanvas")
                    .fields({ node: true, size: true })
                    .exec(async (res) => {
                        const canvas = res[0].node;
                        const ctx = canvas.getContext("2d");
                        console.log(ctx);
                        const dpr = wx.getSystemInfoSync().pixelRatio;
                        canvas.width = res[0].width * dpr;
                        canvas.height = res[0].height * dpr;
                        ctx.scale(dpr, dpr);
                        Notify({
                            type: "success",
                            duration: 5000,
                            message: "绘制中",
                            selector: "#editor-notify",
                        });
                        const WH = await drawPic(
                            ctx,
                            canvas,
                            { ...this.content, ...this.date },
                            this.px, {
                         
                        }
                        ).catch((err) => {
                            Notify({
                                type: "danger",
                                duration: 5000,
                                message: "绘制错误" + err.message,
                                selector: "#editor-notify",
                            });
                            throw err
                        });
                        Notify({
                            type: "success",
                            duration: 2000,
                            message: "保存开始，请稍等。。。",
                            selector: "#editor-notify",
                        });
                        const path = await new Promise((resolve, reject) => {
                            console.log("绘制已经完成");
                            wx.canvasToTempFilePath({
                                fileType: "png",
                                ...WH,
                                canvas,
                                success: function (res) {
                                    var tempFilePath = res.tempFilePath;
                                    ctx.clearRect(
                                        0,
                                        0,
                                        canvas.width,
                                        canvas.height
                                    );
                                    resolve(tempFilePath);
                                },
                                fail: function (res) {
                                    reject(res);
                                },
                            });
                        }).catch((err) => {
                            Notify({
                                type: "danger",
                                duration: 5000,
                                message: "保存画布失败" + err.message,
                                selector: "#editor-notify",
                            });
                        });
                        return this.saveImage(path);
                    });
            } catch (err) {
                Notify({
                    type: "danger",
                    duration: 5000,
                    message: "微信版本过低，" + err.message,
                    selector: "#editor-notify",
                });
            }
        },
        async savePic() {
            if (this.lock) return null;
            this.lock = true;
            Notify({
                type: "success",
                message: "保存中",
                selector: "#editor-notify",
            });
            try {
                await this.getPower();
            } catch (err) {
                Notify({
                    type: "warning",
                    duration: 5000,
                    message: "请在个人界面的小程序权限页面添加保存图片页面",
                    selector: "#editor-notify",
                });
                return null;
            }
            if (this.content.type === "image") {
                await this.downloadImage();
            } else {
                await this.downloadCard();
            }

            this.lock = false;
        },
        saveImage(path) {
            return wx
                .saveImageToPhotosAlbum({
                    filePath: path,
                })
                .then(() => {
                    Notify({
                        type: "success",
                        message: "保存成功",
                        selector: "#editor-notify",
                    });
                })
                .catch((err) => {
                    Notify({
                        type: "danger",
                        message: "保存失败" + err,
                        selector: "#editor-notify",
                    });
                });
        },
        async downloadImage() {
            return wx.cloud
                .downloadFile({
                    fileID: this.content.image,
                })
                .then((res) => res.tempFilePath)

                .then(this.saveImage);
        },
    },
};
</script>

<style lang="less" scoped>
.main {
    height: 100%;
    width: 100%;
    position: relative;
}

.box {
    height: 60%;
    width: 88%;
    justify-content: space-evenly;

    .title {
        position: absolute;
        top: 20rpx;
        font-size: 40rpx;
        font-weight: bold;
    }

    .close {
        position: absolute;
        right: 20rpx;
        top: 20rpx;
    }

    position: relative;
    background-color: #fff;
    border-radius: 16rpx;
}

.options {
    padding: 16rpx;
    border: 4rpx solid;
    color: #969696;
    border-radius: 20rpx;

    .label {
        padding: 8rpx;

        .watermark {
            font-size: 80rpx;
            font-weight: bold;
            margin: 13rpx;
        }

        .desc {
            font-size: 26rpx;
        }
    }

    .download {
        width: 100%;
        font-weight: bold;
    }
}
</style>